/*
 * DSBDirect
 * Copyright (C) 2019 Fynn Godau
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * This software is not affiliated with heinekingmedia GmbH, the
 * developer of the DSB platform.
 */

package godau.fynn.dsbdirect.table.reader;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.util.Log;
import godau.fynn.dsbdirect.Utility;
import godau.fynn.dsbdirect.table.Entry;
import godau.fynn.dsbdirect.table.Table;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import static android.content.Context.MODE_PRIVATE;

public abstract class Reader {
    // Reader is just used as a synonym for Parser

    protected String mHtml;

    public Reader(String html) {
        mHtml = html;
    }

    public abstract ArrayList<Entry> read();

    public ArrayList<Entry> filterUserFilters(@NonNull ArrayList<Entry> entries, Context context) {
        // get sharedPreferences
        final SharedPreferences sharedPreferences = context.getSharedPreferences("default", MODE_PRIVATE);

        if (!sharedPreferences.getBoolean("filter", false)) {
            // Filters are disabled
            return entries;
        }

        String number = sharedPreferences.getString("number", "");
        String letter = sharedPreferences.getString("letter", "");
        String name = sharedPreferences.getString("name", "");

        // Declare adjectives
        boolean displayGeneral = sharedPreferences.getBoolean("displayGeneral", false);
        boolean classFilterActive = letter.length() > 0 || number.length() > 0;
        boolean teacherFilterActive = name.length() > 0;

        if (!classFilterActive && !teacherFilterActive) { // Let's not filter when no filter is enabled
            return entries;
        }


        for (int i = entries.size(); i > 0; i--) {
            Entry e = entries.get(i - 1);

            // Determine whether past should be filtered
            boolean filterPast = sharedPreferences.getBoolean("filterPast", true);

            if (filterPast) {
                // Declare past adjective

                Calendar zeroOClockCalendar = Utility.zeroOClock(Calendar.getInstance());

                long today = zeroOClockCalendar.getTimeInMillis();
                long entry = e.getDate().getTime();

                // Entry is in the past if it was before today
                boolean past = entry < today;

                if (past) {
                    entries.remove(i - 1);

                    // Don't check other criteria as the entry is already gone
                    continue;
                }

            }


            // Declare more adjectives

            boolean unterrichtsfrei = e.getInfo().contains("Unterrichtsfrei") || e.getInfo().contains("Unterrichtsende") || e.getInfo().contains("Unterrichtsschluss");

            boolean classInClass = e.getAffectedClass().contains(number) && e.getAffectedClass().toLowerCase().contains(letter.toLowerCase());
            boolean classInInfo = e.getInfo().contains(number) && e.getInfo().contains(letter);
            boolean affectedClassEmpty = e.getAffectedClass().length() == 0;

            boolean teacherAppears = e.getReplacementTeacher().toLowerCase().contains(name.toLowerCase()) || e.getInfo().contains(name);

            boolean infoOnly = affectedClassEmpty && e.getLesson().length() == 0 && e.getReplacementTeacher().length() == 0 && e.getInfo().length() > 0;

            // first possibility: Unterrichtsfrei / Unterrichtsende / Unterrichtsschluss
            if (unterrichtsfrei) {
                // pass, everyone is interested in that
            // second possibility: class appears or contains
            } else if (

                    (classInClass // test class in affected class
                            || (classInInfo && affectedClassEmpty) // test class in info if no affected class
                    ) && classFilterActive

            ) {
                // pass
            // third possibility: teacher appears
            } else if (teacherAppears && teacherFilterActive) {
                // pass
            // fourth possibility: info only
            } else if (infoOnly && displayGeneral) {
                // pass
            } else {
                // fail
                entries.remove(i - 1);
            }
        }

        /*/ fill in data from sharedPreferences
        inputNumber.setText();
        inputLetter.setText(sharedPreferences.getString("letter", ""));
        inputName.setText(sharedPreferences.getString("name", ""));*/

        return entries;
    }

    public ArrayList<Entry> filterToday(@NonNull ArrayList<Entry> entries) {
        for (int i = entries.size(); i > 0; i--) {
            Entry entry = entries.get(i - 1);

            Date entryDate = entry.getDate();

            Calendar entryCalendar = Calendar.getInstance();
            entryCalendar.setTime(entryDate);

            Calendar todayCalendar = Calendar.getInstance();

            int entryDay = entryCalendar.get(Calendar.DAY_OF_YEAR);
            int todayDay = todayCalendar.get(Calendar.DAY_OF_YEAR);

            int entryYear = entryCalendar.get(Calendar.YEAR);
            int todayYear = todayCalendar.get(Calendar.YEAR);

            boolean yearMatches = entryYear == todayYear;
            boolean dayMatches = entryDay == todayDay;

            boolean sameDay = yearMatches && dayMatches;

            if (!sameDay) {
                entries.remove(entry);
            }
        }

        return entries;
    }

    public static Table[] readTableList(JSONArray jsonArray) throws JSONException {
        ArrayList<Table> tables = new ArrayList<>();

        parsing:
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonTable = jsonArray.getJSONObject(i);
            Date publishedTime = Utility.parseLastUpdatedDate(jsonTable.getString("timetabledate"));

            String url = jsonTable.getString("timetableurl");

            // Test whether url is duplicate
            for (Table t :
                    tables) {
                if (t.getUri().equals(url)) {
                    continue parsing;
                }
            }

            // Not a duplicate; add
            tables.add(new Table(url, publishedTime, jsonTable.getBoolean("ishtml")));

        }

        return tables.toArray(new Table[0]);
    }

    public static String[] readTableGroupnames(JSONArray jsonArray) throws JSONException {
        String[] groupnames = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonTable = jsonArray.getJSONObject(i);
            String groupname = jsonTable.getString("timetablegroupname");

            // For better gazplan support
            groupname = groupname.replace("Vert_Schüler_", "");

            groupnames[i] = groupname;
        }
        return groupnames;
    }
}
